package com.forlove.app.manager;

import android.content.Context;
import android.text.TextUtils;

import com.forlove.app.ForloveApplication;
import com.forlove.app.common.utils.AppPreferenceHelper;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.qselect.login.entity.UserEntity;
import com.forlove.app.qselect.login.entity.UserListEntity;

import org.json.JSONArray;
import org.json.JSONException;

import static android.content.ContentValues.TAG;

/**
 * Created by yjl on 2017/9/28.
 * 用户状态管理类
 */

public class UserManager {
    /**
     * 保存是否第一次打开状态
     *
     * @param context
     * @param state
     */
    public static void saveFirstOpenState(Context context, boolean state) {
        AppPreferenceHelper.getInstance(context).
                putBoolean(PreferenceKeys.KEY_USER_FIRST_OPEN, state);
    }

    /**
     * 获取第一次打开状态，默认true
     *
     * @param context
     * @return true 第一次打开，false 不是第一次打开
     */
    public static boolean getFirstOpenState(Context context) {
        return AppPreferenceHelper.getInstance(context).
                getBoolean(PreferenceKeys.KEY_USER_FIRST_OPEN, true);
    }


    public static String getOldAppVersion(Context context) {
        return AppPreferenceHelper.getInstance(context).getString(PreferenceKeys.APP_VERSION, "");
    }

    public static void saveOldAppVersion(Context context, String version) {
        AppPreferenceHelper.getInstance(context).putString(PreferenceKeys.APP_VERSION, version);
    }


    /**
     * 获取当前登录用户
     *
     * @param context
     * @return
     */
    public static UserEntity getUesrInfo(Context context) {
        // LogUtil.e("yjl", "获取用户信息");
        if (context == null) {
            return null;
        }
        UserListEntity mUsersList = getUserListInfo(context);
        if (mUsersList == null || mUsersList.mUserList == null) {
            LogUtil.d(TAG, "获取用户信息mUserList is null");
            return null;
        }

        int userId = mUsersList.mUserID;
        // 如果没有设置登录的用户id则为无登录用户
        if (userId == 0) {
            return null;
        }
        if (null != mUsersList && mUsersList.mUserList.length() > 0) {
            for (int i = 0; i < mUsersList.mUserList.length(); ++i) {
                UserEntity user = new UserEntity();
                user.parseJSONObject(mUsersList.mUserList.optJSONObject(i));
                if (user.userId > 0 && userId == user.userId) {
                    if (!getUserLoginState(context)) {
                        LogUtil.i(TAG, "用户是未登录状态");
                        // 如果用户未登录则将access_token设置成null
                        user.access_token = "";
                    }
                    // LogUtil.e("获取登录用户的信息：" + user.serializeToString());
                    return user;
                }

            }
        }
        return null;
    }

    /**
     * 获取用户登录状态
     *
     * @param context
     * @return
     */
    public static boolean getUserLoginState(Context context) {
        return AppPreferenceHelper.getInstance(context).getBoolean(PreferenceKeys.IS_LOGIN, false);
    }

    /**
     * 保存用户登录状态
     *
     * @param context
     * @param isLogin
     */
    public static void saveLoginState(Context context, boolean isLogin) {
        if (context == null) {
            return;
        }
        AppPreferenceHelper.getInstance(context).putBoolean(PreferenceKeys.IS_LOGIN, isLogin);
    }

    /**
     * 保存当前登录用户信息 必须要有user id为唯一账户标志
     *
     * @param mUser
     */
    public static void saveUserInfo(Context context, UserEntity mUser) {
        if (mUser == null) {
            return;
        }
        UserListEntity userList = getUserListInfo(context);
        if (userList == null) {
            userList = new UserListEntity();
            userList.mUserList = new JSONArray();
        }
        if (mUser.userId > 0) {
            // 统计登录用户账号
//            MobclickAgent.onProfileSignIn(mUser.userId);
        }
        if (!TextUtils.isEmpty(mUser.password)) {
            mUser.password = "";
        }
        if (null != userList.mUserList && userList.mUserList.length() > 0) {
            for (int i = 0; i < userList.mUserList.length(); ++i) {
                UserEntity user = new UserEntity();
                user.parseJSONObject(userList.mUserList.optJSONObject(i));
                if (mUser.equals(user) || mUser.isSameUser(user)) {
                    // if (mUser.isSameUser(user)) {
                    // 如果是同一个User则替换掉
                    if (mUser.userId > 0) {
                        userList.mUserID = mUser.userId;
                    }
                    try {
                        userList.mUserList.put(i, mUser.serializeToJSONObject());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    // LogUtil.d(TAG, "保存的用户信息1：" +
                    // userList.serializeToString());
                    AppPreferenceHelper.getInstance(context).putString(PreferenceKeys.USER_INFO, userList.serializeToString());
                    return;
                }
            }
            // 直接加入到列表中，如果没有相同的用户
            if (mUser.userId > 0) {
                userList.mUserID = mUser.userId;
            }
            userList.mUserList.put(mUser.serializeToJSONObject());
            if (userList.mUserList.length() > 0) {
                // LogUtil.e("保存的用户信息2：" + userList.serializeToString());
                AppPreferenceHelper.getInstance(context).putString(PreferenceKeys.USER_INFO, userList.serializeToString());
            }
        } else {
            if (mUser.userId > 0) {
                userList.mUserID = mUser.userId;
            }
            userList.mUserList.put(mUser.serializeToJSONObject());
            if (userList.mUserList.length() > 0) {
                // LogUtil.e("保存的用户信息3：" + userList.serializeToString());

                AppPreferenceHelper.getInstance(context).putString(PreferenceKeys.USER_INFO, userList.serializeToString());
            }
            return;
        }

    }

    /**
     * 获取当前保存的所有用户信息
     *
     * @param context
     * @return
     */
    public static UserListEntity getUserListInfo(Context context) {
        if (context == null) {
            return null;
        }

        String userStr =
                AppPreferenceHelper.getInstance(context).getString(PreferenceKeys.USER_INFO, null);

        // LogUtil.d("获取所有登录用户信息：" + userStr);
        if (TextUtils.isEmpty(userStr)) {
            return null;
        }
        UserListEntity userList = new UserListEntity();
        userList.parseJSONString(userStr);
        return userList;
    }


    /**
     * 保存用户年纪
     *
     * @param context
     * @param year
     */
    public static void saveUserAge(Context context, String year) {
        AppPreferenceHelper.getInstance(context).putString(PreferenceKeys.USER_AGE, year);
    }


    public static String getUserAge(Context context) {
        return AppPreferenceHelper.getInstance(context).getString(PreferenceKeys.USER_AGE, "");
    }


    public static void Logout() {
        UserEntity userEntity = getUesrInfo(ForloveApplication.getInstance());
        if (userEntity != null) {
            userEntity.access_token = "";
            saveUserInfo(ForloveApplication.getInstance(), userEntity);
        }
        saveLoginState(ForloveApplication.getInstance(), false);
    }


    /**
     * 保存最新的好友动态的id
     *
     * @param context
     * @param recordId
     */
    public static synchronized void saveNewCircleInfo(Context context, int recordId) {

        AppPreferenceHelper.getInstance(context).putInt(PreferenceKeys.NEW_FRIEND_CIRCLE_INFO, recordId);

    }


    public static synchronized int getNewCircleInfo(Context context) {
        return AppPreferenceHelper.getInstance(context).getInt(PreferenceKeys.NEW_FRIEND_CIRCLE_INFO, 0);
    }


    public static void saveJPUSHId(Context context, String jpushId) {

        AppPreferenceHelper.getInstance(context).putString(PreferenceKeys.JSPUH_REGISTER_ID, jpushId);
    }

    public static String getJPushID(Context context) {
        return AppPreferenceHelper.getInstance(context).getString(PreferenceKeys.JSPUH_REGISTER_ID, "");
    }
}
